package com.apache.flow.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.jbpm.api.ProcessEngine;
import org.jbpm.api.TaskQuery;
import org.jbpm.api.TaskService;
import org.jbpm.api.task.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.apache.common.FlowBaseAction;
import com.apache.core.utils.web.struts2.Struts2Utils;
import com.apache.flow.taskHandler.TaskTag;
import com.apache.flow.vo.TaskVo;
import com.apache.tools.DateUtils;
import com.apache.tools.NumberUtils;
import com.apache.tools.StrUtil;

@Namespace("/flow/core")
@Results({ @Result(name = "approve", location = "flow-approve.action", type = "redirect") })
public class FlowTaskAction extends FlowBaseAction {
	private Logger logger = LoggerFactory.getLogger(FlowTaskAction.class);
	@Autowired
	private ProcessEngine processEngine;

	private String definitionId;//流程定义Id
	private String taskId;//任务Id
	private String page;
	private String rows;
	private String lastUser;

	/**
	 * 默认方法
	 */
	@Override
	public String execute() throws Exception {
		if (loginUser != null && null != loginUser.getUserCname()) {
			lastUser = loginUser.getUserEname();
		} else {
			lastUser = "";
		}
		return SUCCESS;
	}

	/**
	 * 
	 * @return
	 * <p>@description 获取个人待办任务方法
	 * <p>@version 1.0
	 * <p>@author lvcai
	 * <p>@update 2013-7-29 下午06:05:20
	 */
	public String approveData() {
		int pageNo = NumberUtils.getInt(page, 1);
		int pageSize = NumberUtils.getInt(rows, 15);
		int startIndex = (pageNo - 1) * pageSize;
		String assignEname = Struts2Utils.getRequest().getParameter("assignEname");

		TaskService taskService = processEngine.getTaskService();
		String taskAssignee = loginUser.getUserEname();
		if (StrUtil.isNotNull(assignEname)) {
			taskAssignee = assignEname;
		}
		JSONObject json = new JSONObject();
		if (taskAssignee != null) {
			//			List<Task> taskList = taskService.findPersonalTasks(taskAssignee); 
			//			List<Task> list=taskService.findGroupTasks(taskAssignee);
			//			taskList = taskList == null ? list : taskList;
			//			
			//			if(list != null && taskList !=null)
			//				taskList.addAll(list);
			TaskQuery taskQuery = taskService.createTaskQuery();
			int sumCount = taskQuery.assignee(taskAssignee).list().size();
			List<Task> taskList = taskQuery.assignee(taskAssignee).notSuspended().page(startIndex, pageSize)
					.orderDesc(TaskQuery.PROPERTY_CREATEDATE).list();
			List<TaskVo> taskVoList = new ArrayList<TaskVo>();
			String description = null;
			String[] strs = null;
			String isRed = null;
			for (Task task : taskList) {
				TaskVo taskVo = new TaskVo();
				taskVo.setId(task.getId());
				taskVo.setName(task.getName());
				taskVo.setFormResourceName(task.getFormResourceName());
				taskVo.setProcessInstanceId(getInstIdFromExeId(task.getExecutionId()));
				taskVo.setCreateTime(DateUtils.format(task.getCreateTime(), DateUtils.FmtStr.yyyyMMdd_HHmmss.toString()));

				description = task.getDescription();
				strs = description.split(TaskTag.splitTag, -1);
				isRed = StrUtil.doNull(strs[0], "");
				if (!"".equals(isRed)) {//判断是否任务名是否标红提醒
					if (Long.valueOf(isRed) <= new Date().getTime()) {
						taskVo.setIsRed("Y");
					}
				}
				taskVo.setFormId(StrUtil.doNull(strs[1], ""));
				taskVo.setFormName(StrUtil.doNull(strs[2], ""));
				taskVo.setFormInfo(StrUtil.doNull(strs[3], ""));
				taskVo.setFormType(StrUtil.doNull(strs[4], ""));
				taskVo.setLastUser(StrUtil.doNull(strs[5], ""));
				taskVo.setUserName(StrUtil.doNull(strs[6], ""));
				taskVoList.add(taskVo);
			}
			json.put("total", sumCount);
			json.put("rows", taskVoList);
		} else {
			json.put("total", 0);
			json.put("rows", null);

		}
		try {
			Struts2Utils.getResponse().getWriter().write(json.toString());
		} catch (IOException e) {
			logger.debug("得到流程定义数据错误" + e);
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 
	 * @param temp
	 * @return
	 * <p>@description 处理流程实例Id
	 * <p>@version 1.0
	 * <p>@author lvcai
	 * <p>@update 2013-7-29 下午06:07:32
	 */
	private String getInstIdFromExeId(String temp) {
		String data = temp;
		int tt = data.indexOf('.');
		tt = data.indexOf('.', tt + 1);
		if (tt > 0) {
			data = data.substring(0, tt);
		}
		return data;
	}

	private String getXmlInfo(String result, String errmsg, String instFlag) {
		StringBuffer XmlStr = new StringBuffer("<?xml version='1.0' encoding='UTF-8'?><root>");
		XmlStr.append("<result>" + result + "</result><errmsg>" + errmsg + "</errmsg><instFlag>" + instFlag
				+ "</instFlag>");
		XmlStr.append("</root>");
		return XmlStr.toString();
	}

	/**
	 * 
	 * @param xml
	 * @param response
	 * <p>@description 统一输出到客户端
	 * <p>@version 1.0
	 * <p>@author lvcai
	 * <p>@update 2013-7-29 下午06:07:55
	 */
	private void outputXml(String xml, HttpServletResponse response) {
		try {
			response.setContentType("text/xml; charset=UTF-8");
			PrintWriter out = response.getWriter();
			out.print(xml);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public String getDefinitionId() {
		return definitionId;
	}

	public void setDefinitionId(String definitionId) {
		this.definitionId = definitionId;
	}

	public String getTaskId() {
		return taskId;
	}

	public void setTaskId(String taskId) {
		this.taskId = taskId;
	}

	public String getPage() {
		return page;
	}

	public void setPage(String page) {
		this.page = page;
	}

	public String getRows() {
		return rows;
	}

	public void setRows(String rows) {
		this.rows = rows;
	}

	public String getLastUser() {
		return lastUser;
	}

	public void setLastUser(String lastUser) {
		this.lastUser = lastUser;
	}

}
